#!/usr/bin/python3
# -*- coding: utf-8 -*-
import base64
import configparser
import json

import requests
from Crypto.Cipher import AES


def save_token(token):
    config = configparser.ConfigParser()
    config.read('jss.ini')
    config.set("jss", "token", token)
    # write to file
    config.write(open('jss.ini', "w"))
    print("保存token完成")


class JssDevSpider:
    member_token = ''

    def __init__(self):
        # key值（密码）
        self.key = '1234567890123456'.encode("utf-8")
        # 因为在python3中AES传入参数的参数类型存在问题，需要更换为 bytearray , 所以使用encode编码格式将其转为字节格式（linux系统可不用指定编码）
        # vi偏移量
        # 编码
        self.iv = '1571925183403747'.encode("utf-8")
        self.mode = AES.MODE_CBC
        self.BS = AES.block_size
        self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)

        self.base_url = "https://jss.test.zjjushuashua.com/api/"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/70.0.3538.110 Safari/537.36",
            "token": "member_token_68011308e6b9121ab6554d3e1f11dcb6112076"
        }
        self.page = 1

    def encrypt(self, text):
        text = self.pad(text).encode("utf-8")
        crypto = AES.new(self.key, self.mode, self.iv)
        # 目前AES-128 足够目前使用(CBC加密)
        cipher_text = crypto.encrypt(text)
        # base64加密
        return base64.b64encode(bytes(cipher_text))

    def get_content(self, url, data):
        response = requests.post(url=self.base_url + url, headers=self.headers, data=data)
        return response.content

    def login(self, phone, pwd):
        password = self.encrypt(pwd)
        url = "login/password_login"
        # response = requests.post(url=url, headers=self.headers, data={'phone': phone, 'password': password})

        content = self.get_content(url, {'phone': phone, 'password': password})
        html = str(content, 'utf-8')
        print(html)

        results = json.loads(html)
        code = results['code']
        if code == 0:
            print('登录成功')
            token = results['data']['token']
            save_token(token)
            self.set_http_token(token)
            return True
        else:
            print('登录失败')
            return False

    # 商家端-订单列表
    def get_merchant_order_list(self, page):
        content = self.get_content('shop_order/order_list', {
            'type': 0, 'status': 0, 'page': page
        })
        html = str(content, 'utf-8')
        print('商家端-订单列表', html, sep='|')
        return html

    def get_user_follow_list(self, page):
        content = self.get_content('member/follow_list', {'page': page})
        html = str(content, 'utf-8')
        print('用户关注店铺信息', html, sep='|')

    def get_user_collect_list(self, page):
        content = self.get_content('member/collect_list', {'page': page})
        html = str(content, 'utf-8')
        print('用户收藏商品信息', html, sep='|')

    def get_user_coupon_list(self, page, status):
        content = self.get_content('plan_member/plan_get_list', {'page': page, 'status': status})
        html = str(content, 'utf-8')
        print('用户领取优惠券列表', html, sep='|')

    def set_http_token(self, token):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/70.0.3538.110 Safari/537.36",
            "token": token
        }

    def get_courier_info(self, courier_company='京东快递', courier_no='JDV004949936798'):
        content = self.get_content('common/courier_info', {'courier_com': courier_company, 'courier_no': courier_no})
        html = str(content, 'utf-8')
        print('快递信息', html, sep='|')

    def get_user_info(self):
        content = self.get_content('member/wallet', {
        })
        html = str(content, 'utf-8')
        # 格式化打印json
        # json_object = json.loads(html)
        # json_formatted_str = json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ':'))
        # print('用户信息', json_formatted_str, sep='|')
        print('用户信息', html, sep='|')

    def get_recommend_sort(self, sort_type=1):
        content = self.get_content('category/get_recommend', {'type': sort_type})
        html = str(content, 'utf-8')
        print('推荐分类', html, sep='|')

    def get_good_list(self, page, shop_id, keyword='', sort_by='asc', lat='', lng='', city='', category_level=0,
                      sort_type='sales', good_type=0):
        request_map = dict()
        request_map['page'] = page
        if len(shop_id) > 0:
            request_map['shop_id'] = shop_id
        else:
            return
        if len(keyword) > 0:
            request_map['keyword'] = keyword
        request_map['type'] = good_type
        request_map['sort_type'] = sort_type
        if category_level > 0:
            request_map['category_level'] = category_level
        if len(sort_by) > 0:
            request_map['sort_by'] = sort_by
        if len(lat) > 0:
            request_map['lat'] = lat
        if len(lng) > 0:
            request_map['lng'] = lng
        if len(city) > 0:
            request_map['city'] = city
        content = self.get_content('goods/get_list', request_map)
        html = str(content, 'utf-8')
        print('商品列表', html, sep='|')

    def get_nearby_store_list(self, lat='28.17657269042584', lng='112.9750590951538'):
        content = self.get_content('store/nearby_list', {'lat': lat, 'lng': lng})
        html = str(content, 'utf-8')
        print('附近的店铺列表', html, sep='|')
        return html

    def get_comment_info(self):
        # 获取附近的商家列表
        self.get_nearby_store_list('28.188384', '113.010207')
        # json_object = json.loads(html)
        # for data_list in json_object['data']:
        #     store_id = data_list['id']
        #     print('store_id', store_id, sep='|')
        #     # 商品列表
        #     self.get_good_list(self.page, str(store_id))
        # 商品列表
        self.get_good_list(self.page, str(384))
        # 快递信息
        # self.get_courier_info()
        # 推荐分类
        # self.get_recommend_sort(2)

    def get_system_info(self):
        config = configparser.ConfigParser()
        config.read("./jss.ini")

        jss = config['jss']
        username = jss['username']
        password = jss['password']
        token = jss['token']
        print(username, password, token, sep='|')

        if len(token) == 0:
            # 1. 登录
            loginSuccess = self.login(username, password)
            if loginSuccess:
                self.get_user_info()
        else:
            self.set_http_token(token)
            # 用户信息
            # self.get_user_info()
            # 商家端订单列表
            self.get_merchant_order_list(self.page)
            # 用户关注店铺列表
            self.get_user_follow_list(self.page)
            # 用户收藏商品列表
            self.get_user_collect_list(self.page)
            # 用户领取的优惠券
            self.get_user_coupon_list(self.page, 0)

    def run(self):
        # self.get_system_info()
        self.get_comment_info()


if __name__ == '__main__':
    spider = JssDevSpider()
    spider.run()
